package com.dongnaoedu.rpc.redis.spring;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessorAdapter;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;

import com.dongnaoedu.rpc.redis.annotation.RedisRpcClient;
import com.dongnaoedu.rpc.redis.proxy.RedisRpcClientHandler;

@Component
public class RedisRpcClientAnnotationBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {
	private final Log log = LogFactory.getLog(getClass());

	@Autowired
	RedisRpcClientHandler redisRpcClientHandler;

	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
		ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
			@Override
			public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
				RedisRpcClient redisRpcClient = field.getAnnotation(RedisRpcClient.class);
				if (redisRpcClient != null) {
					Class<?> interfaceClazz = field.getType();
					// TODO 这里每次都生成一个新的对象，有没有办法，把这个代理对象的生成，交给spring去做呢？
					Object instance = Proxy.newProxyInstance(interfaceClazz.getClassLoader(),
							new Class[] { interfaceClazz }, redisRpcClientHandler);
					ReflectionUtils.makeAccessible(field);
					field.set(bean, instance);
					log.info("注入@RedisRpcClient: " + bean.getClass() + "#" + field.getName());
				}
			}
		});
		return super.postProcessAfterInstantiation(bean, beanName);
	}
}
